import axios from "axios";
import router from "@/router";
import Syx from "@/utils/syxui/syx-ui.umd.min.js";
import { nativeplacestore } from "@/utils/base";

let { Message } = Syx.ElementUI;

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL: process.env.VUE_APP_DOMAIN_URL,
  timeout: 30000,
});
let i = 0;
// request拦截器
service.interceptors.request.use(
  (config) => {
    i++;
    // 是否需要设置 token
    let token = nativeplacestore.get("login");
    if (token) {
      config.headers["Authorization"] = "Bearer " + JSON.parse(token)["data"];
    }
    return config;
  },
  (error) => {
    router.push("/login");
    return { code: -11111,data:"请重新登录" };
    // Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    i--;
    if (res.data.code == 1000) {
      return res.data;
    } else {
      if (i == 0) {
        Message({
          showClose: true,
          message: res.data,
          type: "warning",
        });
        router.push("/login");
        return { code: -11111,data:"请重新登录" };
      }
    }
  },
  (error) => {
    router.push("/login");
    return { code: -11111,data:"请重新登录" };
    // return Promise.reject(error);
  }
);
export default service;
